<template>
  <a-modal
    style="top: 1px;"
    :title="title"
    :width="width"
    v-model:open="visible"
    :keyboard="false"
    :maskClosable="false"
  >
        <a-form ref="formRef" :model="formState" :rules="formRules">
          <a-row>
            <a-col :span="24">
              <a-form-item name="name" label="模板名称" :labelCol="labelCol2"  :wrapperCol="wrapperCol">
                <a-input v-model:value="formState.name" type="text"></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24">
              <a-form-item name="config" label="模板配置" :labelCol="labelCol2" :wrapperCol="wrapperCol">
                <a-textarea v-model:value="formState.config" :rows="8"></a-textarea>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24">
              <a-form-item name="description" label="备注说明" :labelCol="labelCol2" :wrapperCol="wrapperCol">
                <a-textarea v-model:value="formState.description" :rows="4"></a-textarea>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <template #footer>
          <a-button
            type="primary"
            :loading="uploading"
            style="margin-top: 16px"
            @click="save"
          >
            {{ uploading ? 'Uploading' : '保存' }}
          </a-button>
        </template>
      </a-modal>
</template>
<script setup>
import { ref, nextTick } from 'vue';
import { postAction } from '@/utils/request.js';
import { message } from 'ant-design-vue';

// 定义 props
const props = defineProps(['url', 'data']);
// 定义 emits
const emit = defineEmits(['sync']);
// 定义表单引用
const formRef = ref(null);

const formState = reactive({
  name: '',
  config: '',
  description: ''
});
// 集中定义表单验证规则
const formRules = reactive({
  name: [{required: true, message: '模板名称不能为空', trigger: 'blur'}],
  config: [
    {required: true, message: '模板配置不能为空', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        try {
          // 空或有效json字符，则通过
          if (value) {
            JSON.stringify(JSON.parse(value));
          }
          callback();
        } catch (e) {
          //console.log(e);
          callback('请输入正常json格式');
        }
      },
      trigger: 'blur'
    }
  ],
  description: []
});

// 定义响应式数据
const uploading = ref(false);
const title = ref('新增');
const width = ref('45%');
const visible = ref(false);
const dateFormat = ref('YYYY-MM-DD');

const labelCol = ref({
  xs: { span: 24 },
  sm: { span: 10 }
});
const wrapperCol = ref({
  xs: { span: 24 },
  sm: { span: 14 }
});
const labelCol2 = ref({
  xs: { span: 20 },
  sm: { span: 6 }
});

// 定义方法
const init = () => {
  uploading.value = false;
  nextTick(() => {
    formRef.value?.resetFields(); // 会清验证；其实也会清值
  });
};

const add = (record) => {
  title.value = '新增';
  edit(record);
};

const edit = (record) => {
  init();
  if (record && record.id) {
    title.value = '编辑';
    nextTick(() => {
      Object.assign(formState, record);
    });
  } else { formState.create_by = record.create_by;
  }
  formState.template_type_id = record.template_type_id
  formState.update_by = record.update_by;
  // console.error('record:', JSON.stringify(record));
  visible.value = true;
}

const close = () => {
  visible.value = false;
};

const save = () => {
  uploading.value = true;
  formRef.value
      .validate()
      .then(() => {
        postAction(props.url.template, formState).then((res) => {
          if (res.success) {
            emit('sync');
            close();
            message.success('保存成功!');
          } else {
            let errMsg = res.message;
            const data = res.data;
            if (typeof data === 'string' && data.includes('Violation of UNIQUE KEY')) {
              errMsg = '模板名称已存在，不能使用重复名称！';
            }
            if (errMsg.includes('maximum allowed metadata size')) {
              errMsg = '备注超过最大允许字数！';
            }
            message.error(`${errMsg}保存失败！`);
          }
          uploading.value = false;
        });
      })
      .catch(error => {
        message.warning("表单信息验证失败");
        console.log('error', error);
        uploading.value = false;
      });
}

defineExpose({ add, edit})
</script>
